# coding=utf-8

##############################################################################
#
# twitterpublisher.py
# A class to publish to twitter
#
# Copyright (c) 2007 Webcore Corp. All Rights Reserved.
#
##############################################################################
""" twitterpublisher.py - A class to publish to twitter

$Id: twitterpublisher.py 5 2007-05-06 12:54:22Z shib.ats $
"""

__author__  = 'Atsushi Shibata <shibata@webcore.co.jp>'
__docformat__ = 'plaintext'
__licence__ = 'MIT'

import logging
from datetime import datetime

from feedparser import parse

from utilities import print_exc
from pluginbase import BasePublisher

from twitter import Api

import socket
#socketのタイムアウトを設定
socket.setdefaulttimeout(120)

class TwitterPublisher(BasePublisher):
    """
    Twitterにpublishするクラス
    python-twitterに依存
    http://code.google.com/p/python-twitter/
    """
    def __init__(self, d):
        """
        Publisherの初期化method
        設定値を辞書で引数dに渡す
        設定値の辞書からは，以下のキーを読み込む
        
        username  : Twitterのusername(必須)
        password  : Twitterのpassword(必須)
        template  : Postするmessageのテンプレート(オプション)
        """
        self.username = d.get('username', '')
        self.password = d.get('password', '')
        self.template = d.get('template', '%(link)s : %(title)s')

    def publish(self, settings, item):
        """
        publishを行うmethod
        """
        api = Api()
        message = self.template % item
        if isinstance(message, unicode):
            try:
                message = message.encode('utf-8', 'ignore')
            except:
                pass
        api.PostUpdate(self.username, self.password, message)
        logging.debug("""%s : post to %s, %s""" % \
                            (self.__class__.__name__, self.username, message))

"""
    def test_publish(self, settings, item):
        message = self.template % item
        return message
"""
